#include "core/state/BlackboardStateJoining.h"
#include "core/state/BlackboardStateRunning.h"

BlackboardStateJoining * BlackboardStateJoining::instancePtr = NULL;

BlackboardState * BlackboardStateJoining::instance() {
    if (instancePtr == NULL) {
        instancePtr = new BlackboardStateJoining();
    }
    return instancePtr;
}

void BlackboardStateJoining::packetReceived(BlackboardManager * manager, AbstractPacket * packet) {
    switch (packet->getPacketType()) {
    case JOIN_RESPONSE:
    {
        JoinResponsePacket *joinResponse = (JoinResponsePacket *) packet;
        QList<Node> *list = joinResponse->getNodeList();
        for (int i = 0; i < list->length(); ++i) {
            Node node = list->at(i);
            manager->getNodeListModel()->addNode(node);

            if (node.getAddress() == joinAddress && node.getPort() == joinPort) {
                manager->getNodeListModel()->addNode(manager->getThisNode());
            }
        }
        manager->setSize(joinResponse->getWidth(), joinResponse->getHeight());
        manager->resetImage(joinResponse->getImage());
    }
    break;
    case JOIN_INFO:
    {
        manager->switchState(BlackboardStateRunning::instance());
        manager->initPainting();
    }
    break;
    case JOIN_REQUEST:
    {
        BusyPacket busyPacket;
        manager->sendPacket(&busyPacket);
    }
    break;
    default:
        qWarning() << "Unimplemented case in BlackboardStateJoining::packetReceived";
    }
}

void BlackboardStateJoining::setJoiningNode(const QString & joinAddress, quint16 joinPort) {
    this->joinAddress = joinAddress;
    this->joinPort = joinPort;
}
